# -*- coding: utf-8 -*-
# @File    : run_sql_stam.py
# @Date    : 2021-12-03
# @Author  : Richard

import os
import time

import dmPython
from app.set_log import write_log
from app.get_comp_info import GetCompName


# 数据库操作需要在一个事务里面完成
def run_sql_tra(ip, user, port, data,com_file):
    """
    :param ip:需要执行SQL的服务器IP
    :param user:需要执行SQL的数据库用户
    :param port:需要执行啥情况的数据库端口
    :param data:需要执行SQL的SQL语句，是一个列表
    :param com_file:获取单位名称的字典文件
    :return:返回成功状态
    """
    # ip_list = ["130.20.163.150", "130.20.164.17", "130.20.164.217", "130.20.163.199", "130.20.164.166",
    #            "130.20.164.252", "130.20.164.113", "130.20.164.216"]
    # if ip in ip_list:
    #     db_pwd = "Dmdba@123"
    # else:
    #     db_pwd = "Dmdba@963"
    # 这里是为了快速解决问题，建议使用特定方法使用字典方式获取密码同时加密
    if str(user).upper() == "WEBDOCUMENT":
        re_pwd = "!QAZxsw21qaz"
    elif str(user).upper() == "NOTICEV2":
        re_pwd = "!QAZxsw21qaz"
    elif str(user).upper() == "GOV_MEETING_ROOM_MANAGER":
        re_pwd = "GOV_MEETING_ROOM_MANAGER"
    elif str(user).upper() == "GOV_SYSTEM_MANAGEMENT":
        re_pwd = "GOV_SYSTEM_MANAGEMENT"
    elif str(user).upper() == "GOV_LEADERSHIP_AGENDA":
        re_pwd = "GOV_LEADERSHIP_AGENDA"
    elif str(user).upper() == "MP":
        re_pwd = "Dmdba@963"
    elif str(user).upper() == "PORTAL":
        re_pwd = "Dmdba@963"
    elif str(user).upper() == "OA9_5_0_GXBGT":
        re_pwd = "Dmdba@963"
    # 最高权限用户，有部分数据库节点的sysdba的密码有区别这里要做特殊处理
    elif str(user).upper() == "SYSDBA":
        ip_list = ["130.20.163.150", "130.20.164.17", "130.20.164.217", "130.20.163.199", "130.20.164.166",
                   "130.20.164.252", "130.20.164.113", "130.20.164.216", "130.20.164.5"]
        if ip in ip_list:
            re_pwd = "Dmdba@123"
        else:
            re_pwd = "Dmdba@963"
    # 遍历SQL语句
    # print("data:{0}".format(data))
    # print("user:{0}".format(user))
    # print("port:{0}".format(port))
    # print("ip:{0}".format(ip))
    # time.sleep(10000)
    conn = dmPython.connect(user=user, password=re_pwd, server=ip, port=port)
    cursor = conn.cursor()
    compName = GetCompName(file=com_file)
    # print("compName===={0}".format(compName.get_comp(ip=ip)))
    # time.sleep(1000)
    write_log(msg_info="正在【{0}】执行".format(compName.get_comp(ip=ip)))
    for j in data:
        print("sql:{0}".format(j))
        # print(j)
        write_log(msg_info="开始执行SQL脚本---->:{0}".format(j))
        try:
            # cursor.execute(j)
            write_log(msg_info="执行成功！\n")
            print("执行成功！")
        except Exception as  Err:
            write_log(msg_info="添加表注释和字段失败！！！，SQL脚本---->:{0}".format(j))
            print("Execute sql statement error is:{0},sql info:{1}".format(Err, j))
    conn.commit()
    conn.close()